package com.hlf.modules.sys.service.impl;

import com.hlf.common.constants.Constants;
import com.hlf.common.constants.FileConstants;
import com.hlf.common.exception.BusinessException;
import com.hlf.common.utils.FileOperateUtil;
import com.hlf.common.utils.IdWorkerFactory;
import com.hlf.common.utils.PropertieUtil;
import com.hlf.modules.sys.entity.File;
import com.hlf.modules.sys.mapper.FileMapper;
import com.hlf.modules.sys.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 文件服务层接口实现类
 * 
 * @author shuliangxing
 * 
 * @date 2015-1-14上午11:36:08
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    FileMapper mapper;
    @Autowired
    PropertieUtil propertieUtil;

    @Override
    public int deleteById(Long id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(File record) {
        if (record.getFilId() == null) {
            record.setFilId(IdWorkerFactory.nextId());
        }
        return mapper.insert(record);
    }

    @Override
    public int insertSelective(File record) {
        if (record.getFilId() == null) {
            record.setFilId(IdWorkerFactory.nextId());
        }
        return mapper.insertSelective(record);
    }

    @Override
    public File selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByIdSelective(File record) {
        return mapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateById(File record) {
        return mapper.updateByPrimaryKey(record);
    }

    @Override
    public int deleteSoft(Long id) {
        File entity = new File();
        entity.setFilId(id);
        entity.setStatus(Constants.IS_VALID_FALSE);
        return mapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public List<File> uploadFile(HttpServletRequest request, String filType, String filTypeName, String typePath)
            throws IOException {
        return uploadFile(request, filType, filTypeName, typePath, null, null, null, null);
    }

    public List<File> uploadFile(HttpServletRequest request, String filType, String filTypeName, String typePath,
            String attrName, Long maxSize, Integer minCount, Integer maxCount) throws IOException {
        List<File> fileList = new ArrayList<File>();
        List<Map<String, Object>> list = FileOperateUtil.upload(FileConstants.FILE_UPLOAD_PATH, typePath, attrName, maxSize,
                minCount, maxCount, request);
        for (Map<String, Object> map : list) {
            if (map != null) {
                File file = new File();
                file.setFilOriName((String) map.get(FileOperateUtil.REALNAME));
                file.setFilOriSizeB(Long.valueOf(String.valueOf(map.get(FileOperateUtil.SIZE))).intValue());
                file.setFilOriSuffix((String) map.get(FileOperateUtil.SUFFIX));
                file.setFilSerName((String) map.get(FileOperateUtil.STORENAME));
                file.setFilSerPath( propertieUtil.getPropertie("FILE_UPLOAD_URL") + (String) map.get(FileOperateUtil.STOREPATH));
                file.setFilType(filType);
                file.setFilSerSizeB(Long.valueOf(String.valueOf(map.get(FileOperateUtil.SIZE))).intValue());
                file.setFilTypeName(filTypeName);
                file.setInsertDate(new Date());
                file.setInsertBy((long) 1);
                file.setLastUpdateBy((long) 1);
                file.setLastUpdateDate(new Date());
                file.setStatus(1);
                file.setNormal(1);
                fileList.add(file);
            }
        }

        return fileList;
    }

    @Override
    public List<File> select(String filType, Long foreignId) {
        File file = new File();
        file.setFilType(filType);
        file.setForeignId(foreignId);
        return mapper.selectRelation(file);
    }

    @Override
    public String deleteByForeignId(Long foreignId) {
        mapper.deleteByForeignId(foreignId);
        return Constants.DEFAULT_MSG_SUCCESS;
    }

    @Override
    public int inserts(List<File> list) {
        if (list == null || list.isEmpty()) {
            return 0;
        }

        for (File file : list) {
            if (file.getFilId() == null) {
                file.setFilId(IdWorkerFactory.nextId());
            }
        }

        return mapper.inserts(list);
    }

    @Override
    public File uploadImg(String filType, String filTypeName, String typePath, String oriName, String oriSuffix,
            int oriSize, int size) throws IOException {
        Date date = new Date();
        // 上传路径后面部分
        String sufPath = typePath + "/" + FileOperateUtil.getUploadPathByDate(date);
        String storeName = FileOperateUtil.rename(oriName);
        File file = new File();
        file.setFilId(IdWorkerFactory.nextId());
        file.setFilOriName(oriName);
        file.setFilOriSuffix(oriSuffix);
        file.setFilOriSizeB(oriSize);
        file.setFilSerSizeB(size);
        file.setFilSerName(storeName);
        file.setFilSerPath(sufPath + storeName);
        file.setFilType(filType);
        file.setFilTypeName(filTypeName);
        file.setInsertDate(date);
        file.setInsertBy((long) 1);
        file.setLastUpdateBy((long) 1);
        file.setLastUpdateDate(date);
        return file;
    }

    @Override
    public String deleteByForeignIdAndFilType(Long foreignId, String filType) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int deleteSoftByForeignIdAndFilType(long foreignId, String filType) {
        File entity = new File();
        entity.setForeignId(foreignId);
        entity.setFilType(filType);

        entity.setStatus(Constants.IS_VALID_FALSE);
        return mapper.updateByForeignIdAndFilTypeSelective(entity);

    }

    @Override
    public int updateMerchantImg(File file) {
        mapper.deleteByForeignIdAndFilType(file.getForeignId(), file.getFilType());//删除头像
        if (file.getFilId() == null) {
            file.setFilId(IdWorkerFactory.nextId());
        }
        return mapper.insert(file);//插入头像


    }

    /**
     * 文件集合
     * @param foreignId
     * @return
     */
    @Override
    public List<File> selectByForeignId(Long foreignId) {
        return mapper.selectByForeignId(foreignId);
    }

    /**
     * 删除
     * @param fileId
     */
    @Override
    @Transactional
    public void delete(HttpServletRequest request,Long fileId) {
        File file = selectById(fileId);
        String filSerPath = file.getFilSerPath();
        String fileUploadUrl = propertieUtil.getPropertie("FILE_UPLOAD_URL");
        filSerPath = filSerPath.substring(fileUploadUrl.length());

        // 文件上传路径
        String basePath = FileConstants.FILE_UPLOAD_PATH;
        // 如果服务器上传跟路径为空则使用默认路径
        if (StringUtils.isEmpty(basePath)) {
            basePath = FileOperateUtil.DEFAULT_UPLOADDIR;
        }
        // 如果服务器上传跟路径不是绝对路径("/"开头或盘符开头如“D:\”),则文件存储在项目根目录下
        if (!basePath.startsWith("/") && !basePath.startsWith("\\") && !basePath.contains(":")) {
            basePath = request.getSession().getServletContext()
                    .getRealPath(basePath);
        }
        String delPath = basePath + "/" + filSerPath;
        if (fileId != null) {
            int i = deleteById(fileId);
            if (i == 0){
                throw new BusinessException("删除失败!");
            }
        }
        FileOperateUtil.deleteFile(delPath);
    }

}
